#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   dns_forward.sh
# Version:    1.0
# Date:       2013/10/17
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    02系统基本功能-04网络服务-06DNS-01字符模式-02DNS服务常规配置-01字符方式-02DNS转发服务器配置
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/10/17
#             - Start named service, forward dns
#             Version 1.1,2014/10/30
#             - The second one
#             - change named.conf file for mips  line 77,102,178,203;

# ----------------------------------------------------------------------

##! @TODO: start&stop named service
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_setup1()
{

    trap do_cleanup INT EXIT

    serv=named
    CONF="/etc/named.conf"

    # DNS server is local ip, setup DNS1
    DNS_SERVER=`ifconfig  | grep 'inet ' | grep -m 1 -v '127.0.0.1'  | awk '{print $2}' | tr -d "addr:"`
    [ -z ${DNS_SERVER} ] && { echo "DNS SERVER ip is null"; exit 1; }

    # parse dns server ip for named.conf
    DNS_SERVER_1=`echo ${DNS_SERVER} | awk -F "." '{print $1}'`
    DNS_SERVER_2=`echo ${DNS_SERVER} | awk -F "." '{print $2}'`
    DNS_SERVER_3=`echo ${DNS_SERVER} | awk -F "." '{print $3}'`
    DNS_SERVER_4=`echo ${DNS_SERVER} | awk -F "." '{print $4}'`
    [ -z ${DNS_SERVER_1} -o -z ${DNS_SERVER_2} -o -z ${DNS_SERVER_3} -o -z ${DNS_SERVER_4} ] && { echo "DNS SERVER ip is wrong, pls check"; exit 1; }

    # check owner of /etc/named.conf
    OWNER=`ls -l ${CONF} | awk '{print $3,$4}'`
    if [ "${OWNER}" != "named named" ]; then
        chown named:named ${CONF}
        EchoResult "check owner of ${CONF}"
    fi

    # backup /etc/named.conf
    mv ${CONF} ${CONF}.bak
    EchoResult "backup ${CONF}"
    
    # update named.conf
    TEST_COM="test${DNS_SERVER_4}.com1"

    cat << EOF > ${CONF}
options {
	listen-on port 53 { ${DNS_SERVER}; };
	listen-on-v6 port 53 { ::1; };
	directory 	"/var/named";
	dump-file 	"/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
	allow-query     { any; };
	recursion yes;

	dnssec-enable yes;
	dnssec-validation yes;
	dnssec-lookaside auto;

	/* Path to ISC DLV key */
	bindkeys-file "/etc/named.iscdlv.key";

#	managed-keys-directory "/var/named/dynamic";
};

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};

zone "." IN {
	type hint;
	file "named.ca";
};

zone "${TEST_COM}" IN {
type master;
file "${TEST_COM}.zone";
};
zone "${DNS_SERVER_3}.${DNS_SERVER_2}.${DNS_SERVER_1}.in-addr.arpa" IN {
type master;
file "zone.${TEST_COM}";
};

include "/etc/named.rfc1912.zones";
#include "/etc/named.root.key";
EOF

    # create test.com.zone, zone.test.com
    PATH_TEST_COM=/var/named/
    [ -f "${PATH_TEST_COM}${TEST_COM}.zone" ] && rm -f "${PATH_TEST_COM}${TEST_COM}.zone"
    [ -f "${PATH_TEST_COM}zone.${TEST_COM}" ] && rm -f "${PATH_TEST_COM}zone.${TEST_COM}"
    cat << EOF > ${PATH_TEST_COM}${TEST_COM}.zone
\$TTL 86400
@ IN SOA ${TEST_COM}. root.${TEST_COM}. (
12 ; serial
28800 ; refresh
7200 ; retry
3600000 ; expire
8400 ) ; minimum
@      IN NS www.
www IN A ${DNS_SERVER}
EOF

    cat << EOF > ${PATH_TEST_COM}zone.${TEST_COM}
\$TTL 86400
@ IN SOA ${TEST_COM}. root.${TEST_COM}. (
2012121100 ; serial
28800 ; refresh
7200 ; retry
3600000 ; expire
8400 ) ; minimum
@    IN NS ${TEST_COM}.
${DNS_SERVER_4} IN PTR www.${TEST_COM}.
EOF

    restart_daemon ${serv}

    sleep 3
    # check named start, local
    status_daemon ${serv}  && netstat -nlutp | grep ${serv}
    EchoResult "service ${serv} start on ${DNS_SERVER}"

    #####################################################
    # setup DNS forward server
    TMP_DNS_CONF="/tmp/named.conf$$"
    DNS_FORWARD=${RHOST}

    touch ${TMP_DNS_CONF} && echo "${TMP_DNS_CONF}"

    [ -z ${DNS_FORWARD} ] && { echo "DNS forward server ip is null"; exit 1; }

    # parse dns forward server ip for named.conf
    DNS_FORWARD_1=`echo ${DNS_FORWARD} | awk -F "." '{print $1}'`
    DNS_FORWARD_2=`echo ${DNS_FORWARD} | awk -F "." '{print $2}'`
    DNS_FORWARD_3=`echo ${DNS_FORWARD} | awk -F "." '{print $3}'`
    DNS_FORWARD_4=`echo ${DNS_FORWARD} | awk -F "." '{print $4}'`

    [ -z ${DNS_FORWARD_1} -o -z ${DNS_FORWARD_2} -o -z ${DNS_FORWARD_3} -o -z ${DNS_FORWARD_4} ] && { echo "DNS FORWARD ip is wrong, pls check"; exit 1; }

    # update named.conf
    TEST_COM_FORWARD="test${DNS_FORWARD_4}.com1"

cat << EOF > ${TMP_DNS_CONF}
options {
	listen-on port 53 { ${DNS_FORWARD}; };
	listen-on-v6 port 53 { ::1; };
	directory 	"/var/named";
	dump-file 	"/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
	allow-query     { any; };
	recursion yes;

	dnssec-enable yes;
	dnssec-validation yes;
	dnssec-lookaside auto;

	/* Path to ISC DLV key */
	bindkeys-file "/etc/named.iscdlv.key";

#	managed-keys-directory "/var/named/dynamic";
};

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};

zone "." IN {
	type hint;
	file "named.ca";
};

zone "${TEST_COM_FORWARD}" IN {
type master;
file "${TEST_COM_FORWARD}.zone";
};
zone "${DNS_FORWARD_3}.${DNS_FORWARD_2}.${DNS_FORWARD_1}.in-addr.arpa" IN {
type master;
file "zone.${TEST_COM_FORWARD}";
};

include "/etc/named.rfc1912.zones";
#include "/etc/named.root.key";
EOF

    # create test.com.zone, zone.test.com
    TEST_COM_TMP="/tmp/"
    cat << EOF > ${TEST_COM_TMP}${TEST_COM_FORWARD}.zone
\$TTL 86400
@ IN SOA ${TEST_COM_FORWARD}. root.${TEST_COM_FORWARD}. (
12 ; serial
28800 ; refresh
7200 ; retry
3600000 ; expire
8400 ) ; minimum
@      IN NS www.
www IN A ${DNS_FORWARD}
EOF

    cat << EOF > ${TEST_COM_TMP}zone.${TEST_COM_FORWARD}
\$TTL 86400
@ IN SOA ${TEST_COM_FORWARD}. root.${TEST_COM_FORWARD}. (
2012121100 ; serial
28800 ; refresh
7200 ; retry
3600000 ; expire
8400 ) ; minimum
@    IN NS ${TEST_COM_FORWARD}.
${DNS_FORWARD_4} IN PTR www.${TEST_COM_FORWARD}.
EOF

    # check owner of /tmp/named.conf
    OWNER=`ls -l ${TMP_DNS_CONF} | awk '{print $3,$4}'`
    if [ "${OWNER}" != "named named" ]; then
        chown named:named ${TMP_DNS_CONF}
        EchoResult "check owner of ${TMP_DNS_CONF}"
    fi

    # backup /etc/named.conf on rhost
    ${RSH} -l root -n ${DNS_FORWARD} "mv -f ${CONF} ${CONF}.bak"

    ${RCP} ${TMP_DNS_CONF} ${RUSERNAME}@${DNS_FORWARD}:${CONF}
    ${RCP} "${TEST_COM_TMP}${TEST_COM_FORWARD}.zone" "${TEST_COM_TMP}zone.${TEST_COM_FORWARD}" ${RUSERNAME}@${DNS_FORWARD}:${PATH_TEST_COM}

    ${RSH} -l root -n ${DNS_FORWARD} "command -v systemctl && /bin/systemctl restart ${serv}.service || /sbin/service ${serv} restart"
    RE=`${RSH} -l root ${DNS_FORWARD} \
       "/bin/netstat -ntlp | grep ${serv}"`
    echo "${RE}" | grep ${serv}
    EchoResult "service ${serv} restart test on ${DNS_FORWARD}"


}

##! @TODO:  test dns
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function do_test1()
{
    ############################
    # test on local dns server
    RESULT=`nslookup www.${TEST_COM} ${DNS_SERVER} | grep -iE 'name|address' | grep -v 53`

    sleep 3
    
    echo "${RESULT}"
    
    RESULT_NAME=`echo "${RESULT}" | grep -i 'name' | awk '{print $2}'`
    RESULT_ADDRESS=`echo "${RESULT}" | grep -i 'address' | awk '{print $2}'`

    [ "${RESULT_NAME}" = "www.${TEST_COM}" -a "${RESULT_ADDRESS}" = "${DNS_SERVER}" ]
    EchoResult "test dns server with base config on local dns server"

    ############################
    # test on dns forward server
    RESULT=`${RSH} -l root -n ${DNS_FORWARD} "nslookup www.${TEST_COM_FORWARD} ${DNS_FORWARD} | grep -iE 'name|address' | grep -v 53"`

    sleep 3

    echo "${RESULT}"

    RESULT_NAME=`echo "${RESULT}" | grep -i 'name' | awk '{print $2}'`
    RESULT_ADDRESS=`echo "${RESULT}" | grep -i 'address' | awk '{print $2}'`

    [ "${RESULT_NAME}" = "www.${TEST_COM_FORWARD}" -a "${RESULT_ADDRESS}" = "${DNS_FORWARD}" ]
    EchoResult "test dns server with base config on dns forward server"

    ############################
    # test nxdomain test111.com1 on local dns server
    nslookup www.${TEST_COM_FORWARD} ${DNS_SERVER} | grep -i "NXDOMAIN"
    EchoResult "test forward domain, should return NXDOMAIN"

}

##! @TODO: add forwarders in named.conf, restart dns service
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_setup2()
{
    [ -f ${CONF} ] && sed -i -e "/allow-query/ a\ forwarders { ${DNS_FORWARD}; };" -e 's/dnssec-enable yes/dnssec-enable no/' -e 's/dnssec-validation yes/dnssec-validation no/' ${CONF}

    restart_daemon ${serv}
    EchoResult "add forwarders, restart ${serv}"

}

##! @TODO:  test dns
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function do_test2()
{
    ############################
    # test on dns forward server
    RESULT=`nslookup www.${TEST_COM_FORWARD} ${DNS_SERVER} | grep -iE 'name|address' | grep -v 53`

    sleep 3

    echo -e "nslookup  www.${TEST_COM_FORWARD} ${DNS_SERVER}: \n${RESULT}"

    RESULT_NAME=`echo "${RESULT}" | grep -i 'name' | awk '{print $2}'`
    RESULT_ADDRESS=`echo "${RESULT}" | grep -i 'address' | awk '{print $2}'`

    [ "${RESULT_NAME}" = "www.${TEST_COM_FORWARD}" -a "${RESULT_ADDRESS}" = "${DNS_FORWARD}" ]
    EchoResult "test forward domain with forwarders, should return ${DNS_FORWARD}"

}

##! @TODO:  cleanup tmp files, back up named.conf and stop named service.
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function do_cleanup()
{
    stop_daemon ${serv}
    rm -f "${PATH_TEST_COM}${TEST_COM}.zone" "${PATH_TEST_COM}zone.${TEST_COM}"\
          "${TMP_DNS_CONF}" "${TEST_COM_TMP}${TEST_COM_FORWARD}.zone" "${TEST_COM_TMP}zone.${TEST_COM_FORWARD}"
    [ -f ${CONF}.bak ] && mv -f ${CONF}.bak ${CONF}

    ${RSH} -l root -n ${DNS_FORWARD} "[ -f ${CONF}.bak ] && mv -f ${CONF}.bak ${CONF}; \
                                      rm -f ${PATH_TEST_COM}${TEST_COM_FORWARD}.zone ${PATH_TEST_COM}zone.${TEST_COM_FORWARD}; \
                                      command -v systemctl && /bin/systemctl stop ${serv}.service || /sbin/service ${serv} stop"

}
# include lib files

if [ -z "$SFROOT" ]
then
    CMDLIB=./
    SFROOT=./
else
    CMDLIB=${SFROOT}/testcases/Network_Service
fi

. ${SFROOT}/lib/Echo.sh
. ${SFROOT}/lib/XmlParse.sh
. ${CMDLIB}/lib/Net.sh

. ${CMDLIB}/setup.sh

# get RHOST, RUSERNAME, PASSWORD from config.xml
DATA_FILE="${SFROOT}/testcases/Network_Service/config.xml"
[ -e $DATA_FILE ] || { echo "$DATA_FILE not find, test end."; exit 1; }

XmlParse ${DATA_FILE}

GetValue REHOST ReHost
GetValue RUSERNAME UserName
GetValue PASSWORD RootPasswd

export RHOST=${REHOST}
export RUSERNAME=${RUSERNAME}
export PASSWORD=${PASSWORD}


setup_env || { echo "setup env failed, test end."; exit 1; }
do_setup1
do_test1
EchoResult "${serv} setup dns"

do_setup2
do_test2
EchoResult "testcase: test with forward dns server"
echo ""
